﻿using System.ComponentModel;
using System.Diagnostics;

namespace JPR.TunelProxy.RequestGenerator.ViewModel
{
	/// <summary>
	/// Base class for a ViewModel
	/// </summary>
	internal abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
	{
		private bool _validated;
		private decimal _errors;

		protected ViewModelBase()
		{
			_errors = 0;
			_validated = false;
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;
		protected void OnPropertyChanged(string propName)
		{
			VerifyPropertyName(propName);

			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propName));
			}
			_validated = false;
			_errors = 0;
		}

		#endregion

		[Conditional("DEBUG")]
		[DebuggerStepThrough]
		public void VerifyPropertyName(string propertyName)
		{
			// Verify that the property name matches a real,  
			// public, instance property on this object.
			if (TypeDescriptor.GetProperties(this)[propertyName] == null)
			{
				Debug.Fail("Invalid property name: " + propertyName);
			}
		}

		#region Implementation of INotifyDataErrorInfo

		public bool HasErrors
		{
			get
			{
				if (!_validated)
				{
					Validate();
				}
				return _errors > 0;
			}
		}

		private void Validate()
		{
			//Zkusit deklarativni validaci pres parametry zadane u propertek pomoci [...]. Hledej smudlo. :-)
		}

		public bool IsValid
		{
			get { return !HasErrors; }
		}

		public void NotifyAboutErrors()
		{
			throw new System.NotImplementedException();
		}

		#endregion
	}
}
